package io.dshubs.archives.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import io.dshubs.archives.service.OcrOfBaiduService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <p>
 * 全宗信息表 服务实现类
 * </p>
 *
 * @author tan
 * @since 2021-08-16
 */
@Service
public class OcrOfBaiduServiceImpl implements OcrOfBaiduService {

    @Value("baidu.config.appId")
    public String APP_ID;

    @Value("baidu.config.apiKey")
    public String API_KEY;

    @Value("baidu.config.secretKey")
    public String SECRET_KEY;


    @Override
    public Map<String, String> getImageInfoByBytes(byte[] bytes) throws IOException {
        AipOcr client = getClient();

        // 调用接口
        org.json.JSONObject res = client.basicGeneral(bytes, getOptions());
        System.out.println(res.toString(2));
        Map<String, String> result = (Map)JSONObject.parse("res.toString(2)");
        return result;
    }

    @Override
    public Map<String, String> getImageInfoByFile(String path) {
        AipOcr client = getClient();

        // 调用接口
        path = "F:\\picture\\test\\jiaoyan_text.png";
        org.json.JSONObject res = client.basicGeneral(path, getOptions());
        System.out.println(res.toString(2));
        Map<String, String> result = (Map)JSONObject.parse("res.toString(2)");
        return result;
    }

    @Override
    public Map<String, String> getImageInfoByUrl(String url) {
        AipOcr client = getClient();

        // 调用接口
        org.json.JSONObject res = client.basicGeneralUrl(url, getOptions());
        System.out.println(res.toString(2));
        Map<String, String> result = (Map)JSONObject.parse("res.toString(2)");
        return result;
    }

    private AipOcr getClient() {
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        return client;
    }

    private HashMap getOptions() {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");
        return options;
    }
}
